package at.codebase.web.servlets.user;

import static at.codebase.web.util.i18n.I18NFactory.i18n;

import java.util.ArrayList;

import com.googlecode.objectify.Key;

import at.codebase.core.LinkCreator;
import at.codebase.db.dao.EItemDao;
import at.codebase.db.entities.EImage;
import at.codebase.db.entities.EItem;
import at.codebase.web.templates.MainTemplate;
import at.codebase.web.templates.UserProfileTemplate;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.i10n.L10N;
import at.codebase.web.util.template.Template;
import at.codebase.web.util.template.TemplateEngine;

public class UserItems extends AUserProfile {

	@Override
	void buildUserPage(MainTemplate mainTemplate, UserProfileTemplate userProfileTemplate, RequestInformation requestInfo, UserLevel level, RequestType requestType) {
		mainTemplate.setTitle(i18n(requestInfo.getLocale()).string("userItems_header"));
	
		Template userItemsT = TemplateEngine.getTemplate("user/site_profile_items.html");
		
		ArrayList<EItem> items = EItemDao.getItemsBySeller(requestInfo.getUser().getId());
		ArrayList<Template> itemTemplates = new ArrayList<Template>();

		for(EItem item:items){
			Template unitTemplate = TemplateEngine.getTemplate("user/site_profile_items_item_unit.html");
			ArrayList<Key<EImage>> images = item.getImageKeys();
			if(images.size() > 0){
				unitTemplate.setText("imageUrl", "/service/image?id="+images.get(0).getId()+"&w=110&h=110");
			}else{
				unitTemplate.setText("imageUrl", "/images/no_image_available.png");
			}
			
			unitTemplate.setText("itemId", item.getId().toString());
			unitTemplate.setHTML("title", LinkCreator.itemLink(item.getId(), item.getTitle()));
			String description = item.getDescription();
			if(description.length() > 180)
				description = description.substring(0, 180)+"... ";
			unitTemplate.setText("description", description);
			unitTemplate.setHTML(
					"time",
					i18n(requestInfo.getLocale()).string(
							"search_itemList_createTime",
							L10N.formatDate(requestInfo.getLocale(), item.getTimeCreate())/*,
							L10N.formatTime(requestInfo.getLocale(), item.getTimeCreate())*/));
			unitTemplate.setHTML("price",
					i18n(requestInfo.getLocale()).string(
							"search_itemList_price",
							L10N.formatMoney(requestInfo.getLocale(),
									item.getPrice())));
			itemTemplates.add(unitTemplate);
		}
		
		userItemsT.setTemplates("itemList", itemTemplates);		

		userProfileTemplate.setContent(userItemsT);
	}

}